<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage, dayjs } from 'element-plus'
import { GetDetail, PostCreateLiving, PostModifyLiving } from '@/api/modules/living'
import { GetOptionData } from '@/api/modules/qiwei'
import detailStore from '@/store/modules/cacheData'

const route = useRoute()
const id = route.query.id
const router = useRouter()
const detailData = detailStore()

// const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<any>({
  anchor_userid: '',
  theme: '',
  living_start: '',
  endTime: '',
  living_duration: '',
  description: '',
  type: 0,
  agentid: 0,
  remind_time: 0,
  activity_cover_mediaid: '',
  activity_share_mediaid: '',
  activity_detail: {
    description: '',
    image_list: [],
  },
})

const rules = reactive({
  anchor_userid: [
    { required: true, message: '请选择发起者', trigger: 'blur' },
  ],
  theme: [
    { required: true, message: '请输入直播标题', trigger: 'blur' },
  ],
  living_start: [
    { required: true, message: '请选择开始时间', trigger: 'blur' },
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'blur' },
  ],
  living_duration: [
    { required: true, message: '请输入直播持续时长', trigger: 'blur' },
  ],
})

const ruleFormOption = reactive({
  livingType: [
    { value: 0, label: '通用直播' },
    { value: 1, label: '小班课' },
    { value: 2, label: '大班课' },
    { value: 3, label: '企业培训' },
    { value: 4, label: '活动直播' },
  ],
  userIdOption: [],
})

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }

      // console.log(params)
      if (params.type === 4) {
        params.description = ''
      }
      else {
        params.activity_detail.description = ''
      }

      if (Number(params.remind_time) === 0) {
        ElMessage.error('提醒时间不能为0。')
        return
      }

      const startDayjs = dayjs(params.living_start)
      const endDayjs = dayjs(params.endTime)
      params.living_duration = endDayjs.diff(startDayjs, 'second')
      // console.log(params)

      // if (params.living_duration < 600) {
      //   ElMessage.error('直播持续时长不能小于10分钟。')
      //   return
      // }

      delete params.endTime
      // console.log(params)

      if (id) {
        params.living_duration = Number(params.living_duration)
        // 将开始时间转为Unix时间戳

        params.living_start = dayjs(params.living_start).unix()

        params.livingid = id
        delete params.anchor_userid
        delete params.agentid
        delete params.activity_share_mediaid
        delete params.activity_cover_mediaid
        delete params.activity_detail
        PostModifyLiving(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('修改成功')
            detailData.EmptyLiving()
            router.push({ name: 'livingIndex' })
          }
          else {
            ElMessage.error(`操作失败。 ${res.errors}`)
          }
        })
      }
      else {
        if (!dayjs(params.living_start).isAfter(dayjs())) {
          ElMessage.error('预约直播时间不能是之前。')
          return
        }

        params.living_duration = Number(params.living_duration)
        // 将开始时间转为Unix时间戳

        params.living_start = dayjs(params.living_start).unix()

        PostCreateLiving(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.EmptyLiving()
            router.push({ name: 'livingIndex' })
          }
          else {
            ElMessage.error(`操作失败。 ${res.errors}`)
          }
        })
      }
    }
  })
}

// 图片上传回调
function handleUploadSuccess(url: string, key: string) {
  ruleForm.value[key] = url
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberLiving(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data.livingInfo
        ruleForm.value.endTime = ruleForm.value.living_start + ruleForm.value.living_duration
        ruleForm.value.living_start = dayjs.unix(ruleForm.value.living_start)
        ruleForm.value.endTime = dayjs.unix(ruleForm.value.endTime)
      }
      else {
        ElMessage.error('获取直播详情失败。')
      }
    })
  }
  else {
    ruleForm.value = detailData.GetLiving()
  }
  await GetOptionData().then((res: any) => {
    if (res.statusCode === 200) {
      ruleFormOption.userIdOption = res.data.dept_user
    }
    else {
      ElMessage.error('获取发起者信息失败。')
    }
  })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm" :rules="rules">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol v-if="!id" :md="8">
            <ElFormItem label="发起者" prop="anchor_userid">
              <el-select v-model="ruleForm.anchor_userid" placeholder="请选择发起者" clearable>
                <el-option v-for="items in (ruleFormOption.userIdOption as any)" :key="items.userid" :label="items.userid" :value="items.userid" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="直播标题" prop="theme">
              <el-input v-model="ruleForm.theme" placeholder="请输入直播标题" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="类型">
              <el-select v-model="ruleForm.type" placeholder="请选择类型" clearable>
                <el-option v-for="items in ruleFormOption.livingType" :key="items.value" :label="items.label" :value="items.value" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="开始时间" prop="living_start">
              <el-date-picker
                v-model="ruleForm.living_start"
                type="datetime"
                placeholder="请选择开始时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="结束时间" prop="endTime">
              <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="请选择结束时间"
              />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="直播持续时长" prop="living_duration">
              <el-input
                v-model="ruleForm.living_duration"
                placeholder="请输入直播持续时长"
              >
                <template #append>
                  S
                </template>
              </el-input>
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="直播开始前多久提醒用户（相对于开始时间）">
              <el-input
                v-model="ruleForm.remind_time"
                placeholder="请输入直播持续时长"
              >
                <template #append>
                  S
                </template>
              </el-input>
            </ElFormItem>
          </ElCol>
          <!-- <ElCol v-if="!id" :md="8">
            <ElFormItem label="授权方安装的应用agentid">
              <el-input v-model="ruleForm.agentid" placeholder="请输入agentid" />
            </ElFormItem>
          </ElCol> -->
          <ElCol v-if="ruleForm.type !== 4" :md="24">
            <ElFormItem label="直播简介">
              <el-input v-model="ruleForm.description" placeholder="请输入直播简介" type="textarea" maxlength="100" style="max-width: 800px;" />
            </ElFormItem>
          </ElCol>
          <ElCol v-else :md="16">
            <ElFormItem label="活动直播简介">
              <el-input v-model="ruleForm.activity_detail.description" placeholder="请输入活动直播简介" type="textarea" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="!id" :md="8">
            <ElFormItem label="直播间封面图">
              <ImageUpload
                :size="5" width="auto" :height="150" :url="ruleForm.activity_cover_mediaid" :ext="['png', 'jpg']" apiselect="qiwei"
                @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'activity_cover_mediaid')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="!id" :md="8">
            <ElFormItem label="直播间分享卡片图">
              <ImageUpload
                :size="5" width="auto" :height="150" :url="ruleForm.activity_share_mediaid" :ext="['png', 'jpg']" apiselect="qiwei"
                @on-success="(imgUrl) => handleUploadSuccess(imgUrl, 'activity_share_mediaid')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="!id" :md="24">
            <ElFormItem label="活动直播附图">
              <ImagesUpload
                :height="200" :width="300" :size="5" :url="ruleForm.activity_detail.image_list" :max="5" :ext="['jpg', 'png']" apiselect="qiwei"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
